package com.autoool.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author sam
 * 2021/7/4 21:33
 * @description
 * @editor
 * @description
 */
public class OkHttpUtil {

    private static OkHttpClient client = new OkHttpClient();

    public static String doGet(String url) throws IOException {
        return doGet(url, new HashMap<>());
    }

    public static String doGet(String url, Map<String, Object> query) throws IOException {
        return doGet(url, Collections.EMPTY_MAP, query);
    }

    public static String doGet(String url, Map<String, Object> header, Map<String, Object> query) throws IOException {
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url).build();

        HttpUrl.Builder urlBuilder = request.url().newBuilder();
        Headers.Builder headerBuilder = request.headers().newBuilder();
        Iterator<Map.Entry<String, Object>>
                headerIterator = header.entrySet().iterator();
        headerIterator.forEachRemaining((e) -> {
            headerBuilder.add(e.getKey(), (String) e.getValue());
        });

        Iterator<Map.Entry<String, Object>> queryIterator = query.entrySet().iterator();
        queryIterator.forEachRemaining(e -> {
            urlBuilder.addQueryParameter(e.getKey(), (String) e.getValue());
        });

        builder.url(urlBuilder.build()).headers(headerBuilder.build());
        Response response = client.newCall(builder.build()).execute();
        return response.body().string();
    }


}
